package Lee_code;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author blh
 * @date 2024年08月02日 19:58
 */
public class Lee_316_82 {
    public String removeDuplicateLetters(String s) {
        int len = s.length();
        StringBuilder res = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (res.length() == 0 || res.indexOf(String.valueOf(c)) == -1) {
                res.append(c);
            }
            if (res.indexOf(String.valueOf(c)) != -1) {
                int first = res.indexOf(String.valueOf(c));
                if (first + 1 <= res.length() - 1){
                    int next = first + 1;
                    if (s.charAt(next) < s.charAt(first)){
                        res.deleteCharAt(first);
                        res.append(c);
                    }
                }
                else if (c > s.charAt(s.length()-1)){
                    res.deleteCharAt(first);
                    res.append(c);
                }
            }
        }
        return res.toString();
    }
}
